<template>
    <div class="ele-body">
      <!-- 搜索表单 -->
      <!-- <instokcSearch @search="reload"  /> -->
      <!-- 数据表格 -->
      <el-card shadow="never">
        <ele-pro-table ref="table"  row-key="id" :columns="columns" :datasource="datasource"  :need-page="false" :cell-style="cellStyle"  @done="onDone"  :height="tableHeight" :full-height="tableFullHeight" >
          <!-- 表头工具栏 -->
          <template slot="toolbar">
            <el-button
              v-permission="'Inventory_OpenInstock_Add'"
              size="small"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="openEdit({},'1')"
            >
              添加
            </el-button>
            <el-button
              v-permission="'Inventory_OpenInstock_Export'"
              size="small"
              icon="el-icon-upload2"
              class="ele-btn-icon"
              @click="reportexcel"
            >
              导出
            </el-button>
            <el-upload   ref="upload" size="small" :show-file-list="false" style="display: inline; margin-left: 10px;" action="#" :auto-upload="false" :on-change="handleChange" :limit="1">
              <el-button type="button" size="small" v-permission="'Inventory_OpenInstock_ProductAdd'"
                  class="ele-btn-icon">
                  <i class="el-icon-download"></i><span>导入</span>
              </el-button>
            </el-upload> &nbsp;
            <el-button
              size="small"
              icon="el-icon-download"
              class="ele-btn-icon"
              @click="download"
              v-permission="'SaleOrder_TemplateDownload'"
            >
              导入模板下载
            </el-button>
            <!-- <div class="ele-space" style="float: right; margin-top: 5px;">
              <div class="list-tool-item" style="margin-right: 5px;">
                <span>作废数据</span>&nbsp;
                <el-switch
                  :active-value= 1
                  :inactive-value= 0
                  v-model="isDeleted"
                  @change="editState"
                  >
                </el-switch>
              </div>
              <div class="list-tool-divider" style="margin-right: 5px;">
                <el-divider direction="vertical" />
              </div>
          </div> -->
          </template>
          <!-- 标题列 -->
          <template slot="status" slot-scope="{ row }">
            <el-tag type="danger" v-if="row.status==1">{{ row.statusDesc }}</el-tag>
            <el-tag type="success" v-else-if="row.status==5">{{ row.statusDesc }}</el-tag>
          </template>
          <!-- 标题列 -->
          <template slot="clearAmount" slot-scope="{ row }">
            {{ row.clearAmount }}
          </template>
          <!-- 标题列 -->
          <template slot="inAmount" slot-scope="{ row }">
            ￥{{ row.inAmount }}
          </template>
          <!-- 操作列 -->
          <template slot="action" slot-scope="{ row }"  >
            <el-link type="primary" v-show="row.status!=5" v-permission="'Inventory_OpenInstock_Update'" :underline="false"  icon="el-icon-edit"  @click="openEdit(row,'2')" >修改</el-link>
            <!-- <el-popconfirm  class="ele-action" title="确定要作废吗？"  v-show="row.status!=5 && row.deleted!=1"   @confirm="remove(row)" >
              <el-link type="danger" v-permission="'Inventory_OpenInstock_Delete'" slot="reference" :underline="false"  icon="el-icon-delete" >作废</el-link>
            </el-popconfirm> -->
            <el-link type="info"  :underline="false"  icon="el-icon-view"  @click="openEdit(row,'3')" >详情</el-link>
          </template>
        </ele-pro-table>
      </el-card>
      
      <!-- 编辑弹窗 -->
      <instockEdit :data="current" :visible.sync="showEdit" @done="reload" :btnIndex="btnIndex"/>
      <!-- 导出数据 -->
      <ExportDialog ref="ExportDialog"></ExportDialog>
    </div>
  </template>
  
  <script>
    
    import upload from "@/components/UpLoad";
    import { removePageTab } from '@/utils/page-tab-util';
    import ExportDialog from '@/components/Excel/ExportDialog'
    import instockEdit from './components/instock-edit.vue';
    import { QueryInorderByCondition,DeleteInorder,QueryInorderItemByCondition,ImportExcel } from '@/api/inventory/inorder';

    export default {
      name: 'Openinstock',
      components: {instockEdit,ExportDialog},
      mixins: [upload],
      data() {
        return {
          // 表格列配置
          columns: [
            {columnKey: 'index', type: 'index', width: 50, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号',},
            {prop: 'inOrderNo', label: '入库单号', showOverflowTooltip: true, sortable: 'inOrderNo',align: 'center',},
            {
              prop: 'inDate', label: '入库日期', showOverflowTooltip: true, align: 'center',sortable: 'inDate',
              formatter: (row, column, cellValue) => {return this.$util.toDateString(cellValue,"YYYY-MM-DD");}
            },
            {prop: 'operatorName', label: '经办人', showOverflowTooltip: true, align: 'center',sortable: 'operatorName',},
            {prop: 'inAmount', label: '入库金额', showOverflowTooltip: true, align: 'center', sortable: 'inAmount',},
            // {prop: 'clearAmountCn', label: '费用明细总额', showOverflowTooltip: true, align: 'center',sortable: 'clearAmountCn',},
            {prop: 'status', label: '状态', slot:'status',align: 'center', fixed: 'right', },
            {columnKey: 'action', label: '操作', width: 250, align: 'center', resizable: false,slot: 'action', hideInSetting: true, showOverflowTooltip: true, fixed: 'right', }
          ],
          billNo:'',
          //是否详情
          btnIndex: '1',
          isBf: 0,
          isDeleted: 0,
          fixedHeight:true,
          // 当前编辑数据
          current: null,
          // 是否显示编辑弹窗
          showEdit: false,
          // 全部数据
          projectList: [],
          // 导出列
          exportList: [
            { name: "入库单号", keys: "inOrderNo", status: true },
            { name: "入库日期", keys: "inDate", status: true },
            { name: "经办人", keys: "operatorName", status: true },
            { name: "入库金额", keys: "inAmount", status: true },
            // { name: "费用明细总额", keys: "clearAmount", status: true },
          ],
           // 导出补发列
           exportListBF: [
            {keys: 'productName', name: '产品名称', status: true,},
            {keys: 'productCode', name: '产品编号', status: true,},
            // {keys: 'unitDesc', name: '单位', status: true, },
            // {keys: 'spc', name: '规格', status: true, },
            // {keys: 'costPrice', name: '成本单价', status: true, },
            // {keys: 'totalPrice', name: '金额', status: true, },
            // {keys: 'purQty', name: '应入数量', status: true,  },
            {keys: 'qty', name: '入库数量', status: true,  },
            // {keys: 'actRepairQty', name: '应补数量', status: true, },
            // {keys: 'awaitQty', name: '待补数量', status: true,},
            // {keys: 'repairQty', name: '已补数量', status: true, },
            // {keys: 'PurAmount', name: '应入金额', status: true, },
            {keys: 'totalPrice', name: '入库金额', status: true, },
            // {keys: 'actRepairAmount', name: '应补金额', status: true,},
            // {keys: 'repairAmount', name: '已补金额', status: true,},
          ]
        };
      },
      created(){
        this.billNo = this.$route.query.billNo;
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 250px)' : void 0;

          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 126px)' : null;

          return fh;
        },
      },
      methods: {
        /* 表格数据源 */
        async datasource(params) {
          params.where.pageindex = params.page;
          params.where.pagesize = params.limit;
  
          //添加排序
          if(params.order.order == null || params.order.order == undefined){
            params.where.orderBys = [{ sort: "createDate", order: 1, }];
          }else{
            params.where.orderBys = [];
            params.where.orderBys.push({sort:params.sorter.column.sortable,order:params.order.order=='asc'?0:1});
          }

          if(!params.where.conditions)params.where.conditions= [];

          if(this.billNo){
            params.where.conditions.push({
              key:"inOrderNo",
              operator: 0,
              value: this.billNo,
            });
          }
         
          let delIndex = params.where.conditions.findIndex((g)=>{
            return g.key == 'deleted';
          })

          let actQtyIndex = params.where.conditions.findIndex((g)=>{
            return g.key == 'actRepairQty';
          })

          if(actQtyIndex>=0){
            params.where.conditions.splice(actQtyIndex,1)
          }

          if(delIndex>=0){
            params.where.conditions.splice(delIndex,1)
            params.where.conditions.push({ key:"deleted", operator: 0, value: this.isDeleted})
          }else{
            params.where.conditions.push({
              key:"deleted",
              operator: 0,
              value: this.isDeleted,
            });
          }

          params.where.conditions.push({key:"inOrderType",operator: 0,value:  0,});

          let data = await QueryInorderByCondition(params.where);

          if(data && data.items){
            data.items.map((m)=>{
              m.grey = this.isDeleted;
            })
          }

          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
          
          return {
              list:data.items,
              count:data.totalrecords,
          };
        },


        editState(){
          this.reload();
          this.reloadBf();
        },

        /* 表格渲染完成回调 */
        onDone({ data }) {
          this.supplierList = data;
        },
        /* 刷新表格 */
        reload(where) {
          
          this.$refs.table.reload({ where: where });
        },

        /* 跳转到采购单 */
        clickPurOrder(item) {
          removePageTab({ key: '/businesshandling/purordermanager' });
          this.$nextTick(() => {
            this.$router.push({path: '/businesshandling/purordermanager', query: { "billNo": item.Value} });
          });
        },

        /**
         * 显示编辑
         * @param row 当前行对像
         */
        openEdit(row,index) {
          removePageTab({ key: '/basicdatamanager/openinstockmanager/instockedit' });
          this.$nextTick(() => {
            this.$router.push({path: '/basicdatamanager/openinstockmanager/instockedit', query: { "inorderId": row.id,"isUpdate":index} });
          });
        },
        /* 删除 */
        remove(row) {
          const loading = this.$loading({ lock: true });
          DeleteInorder(row.id)
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        },

         /*下载模板*/
         download(row){
          let a = document.createElement('a')
          a.href = "http://47.120.36.89:8091/file/importtemplates/initstock.xls";
          a.download = '期初入库模板.xlsx'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },

        /* 导出 */
        reportexcel(pams) {
          //初始化参数
          let params = {
            pagesize: 0,
            pageindex: 1,
            conditions: [],
            orderBys: [{ sort: "createDate", order: 1, }],
          };
          //加载进度条
          const loading = this.$loading({ lock: true });
          //重新请求查询
          this.$refs.table.doRequest(({ where }) => {
          if(where){
            params.orderBys = where.orderBys;
            params.pageindex = where.pageindex;
            params.conditions = where.conditions;
          }
          //查询数据
          QueryInorderByCondition(params)
            .then((data) => {
              loading.close();
              this.$refs.ExportDialog.showEdits = true
              this.$refs.ExportDialog.checkList = this.exportList
              this.$refs.ExportDialog.titleName = "入库单列表"
              this.$refs.ExportDialog.dataList = data.items;
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
          });
        },
        
        /* 样式 */
        cellStyle(param){
          let cellStyle;
          const { row, column, rowIndex, columnIndex } = param;
          switch(row.grey == 1){
            case true:
              cellStyle = 'background-color: RGB(240,242,245)';
              break;
            default:
              cellStyle = '';
              break;
          }
          return cellStyle;
        },

        //导入
        handleChange(file) {
          let obj = {
            file: file.raw, // 文件流
            fileName: file.name, // 文件名称
            fileType: 2, // 文件类型(1:图片,2:文件)
          }
          this.uploadExeclPorts(obj);
        },

        async uploadExeclPorts(obj) {
          let param2 = new FormData();
          param2.append('file', obj.file);

          ImportExcel(param2).then((d)=>{

            if(d.code == 200){
              this.$message.success(d.data);

              this.reload();

            }else{

              if(d.data== null || d.data ==''){
                this.$message.error(d.msg);
              }else{

                this.$confirm('数据导入异常,请下载异常信息', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.downloadExeclError(d.data);
                }).catch(() => {
                          
                });
              }
            }
            
            this.$refs["upload"].clearFiles();
            this.reload();
          }).catch(e => {
            this.$message.error(e)
            this.$refs["upload"].clearFiles();
            this.reload();
          });
        },

        downloadExeclError(url) {
          let a = document.createElement('a')
          a.href = url
          a.download = '期初库存异常.xlsx'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },
      }
    };
  </script>
   <style lang="scss" scoped>
  
   /*总计字体颜色
   ::v-deep .el-table__footer-wrapper tbody td {
      color: var(--color-primary);
      cursor: pointer;
    }*/
  </style>